package com.javastudy.autowiredStudy.operationClass;

import com.javastudy.autowiredStudy.strategy.ListConverter;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

import static sun.security.krb5.internal.crypto.Nonce.value;

/**
 * @author madonghui
 * @title: ListConverterOperation
 * @projectName javaproject
 * @description: TODO
 * @date 2021/9/59:26 上午
 */
@Repository
public class ListConverterOperation implements ApplicationListener<ContextRefreshedEvent> {
    /**
     * 存放集合转换器对象的集合   key是注解的value内容，value是注解标记的类实例
     */
    private static Map<String, Function> converterMap = null;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(ListConverter.class);

        //遍历ioc中当前注解标记的bean
        if (MapUtils.isNotEmpty(beansWithAnnotation)){
            converterMap = new HashMap<>(16);
            beansWithAnnotation.forEach((key,value)->{
                ListConverter annotation = value.getClass().getAnnotation(ListConverter.class);
                String code = annotation == null?null:annotation.value();
                if (StringUtils.isNotBlank(code)){
                    converterMap.put(code, (Function) value);
                }
            });
        }
    }

    /**
     * 提供外部访问入口
     * @param code
     * @param src
     * @return
     */
    public List<? extends Object> convert(String code, Object src){
        return (List<? extends Object>) converterMap.get(code).apply(src);
    }
}
